﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Stu_sys.Entity;
using Stu_sys.Models;
using Stu_sys.utils;
using System.Text.Json;

namespace Stu_sys.Controllers
{
    public class RoleController : Controller
    {

        private readonly MysqlContext _mysqlContext;
        public RoleController(MysqlContext mysqlContext) 
        {
            _mysqlContext = mysqlContext;
        }
        public IActionResult RoleList()
        {
            return View();
        }

        [HttpGet]
        public IActionResult GetRoleList() 
        {
            var attrStr = MyUtils.GetAttributeToJsonStr(typeof(RoleViewModel));
            var roleList=_mysqlContext.Roles.ToList();
            var roleStr = JsonSerializer.Serialize(roleList);
            var data = new
            {
                attr = attrStr,
                row = roleStr
            };
            return Json((data));
        }

        [HttpPost]
        public IActionResult AddRole(Role role)
        {
            bool isExist = IsExistRoleName(role);
            if (isExist)
            {
                return Json(0);
            }
            _mysqlContext.Roles.Add(role);
            var res= _mysqlContext.SaveChanges();
            return Json(res);
        }

        [HttpPost]
        public IActionResult EditRole(Role role)
        {
            if (role.RoleName=="")
            {
                return Json(-1);
            }
            bool isExist = IsExistRoleName(role);
            if (isExist)
            {
                return Json(0);
            }

            var r = _mysqlContext.Roles.Where(d => d.RoleId == role.RoleId).FirstOrDefault();
            r!.RoleName = role.RoleName;

            _mysqlContext.Roles.Update(r);
            var res = _mysqlContext.SaveChanges();
            return Json(res);
        }

        [HttpPost]
        public IActionResult DelRole(Role role)
        {
            if (role == null)
            { 
                return BadRequest(string.Empty);
            }
            var r = _mysqlContext.Roles.Single(r=>r.RoleId==role.RoleId);
            _mysqlContext.Remove(r);
            var res= _mysqlContext.SaveChanges();
            return Json(res);
        }

        /// <summary>
        /// 是否存在角色名
        /// </summary>
        /// <param name="角色名"></param>
        /// <returns></returns>
        private bool IsExistRoleName(Role role)
        {
            var roles = _mysqlContext.Roles.Where(r => r.RoleName == role.RoleName).ToList();
            if (roles.Count > 0)
            {
                return true;
            }
            else
            { 
                return false;
            }
        }
    }
}
